package main;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.ideaframe.core.util.DataRow;
import cn.ideaframe.core.util.DataTable;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFReportUtil {
	Document document;

	DocumentInfo docInfo;
	BaseFont bfChinese = null;

	public PDFReportUtil(DocumentInfo docInfo) {
		if (docInfo.pageSize == null) {
			docInfo.pageSize = PageSize.A4;
		}
		this.docInfo = docInfo;
		Rectangle rectPageSize = new Rectangle(docInfo.pageSize);// A4纸张
		if (docInfo.isHor()) {
			document = new Document(rectPageSize.rotate(),
					docInfo.getLeftMargin(), docInfo.rightMargin,
					docInfo.topMargin, docInfo.bottomMargin);// 左、右,上、下间距
		} else {
			document = new Document(rectPageSize, docInfo.getLeftMargin(),
					docInfo.rightMargin, docInfo.topMargin,
					docInfo.bottomMargin);// 左、右,上、下间距
		}

		try {

			if (null == docInfo.getFontpath()) {
				bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
						false);
			} else {
				bfChinese = BaseFont.createFont(docInfo.getFontpath(),
						BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void genPDF(DataTable datalist, DataTable headers,
			DataTable footers, String path) {

		Font textfont = new Font(bfChinese, docInfo.getDefFontSize(),
				Font.NORMAL);

		FileOutputStream out;
		try {
			out = new FileOutputStream(new File(path));
			PdfWriter writer = PdfWriter.getInstance(document, out);

			ReportHeaderFooter headerfooter = new ReportHeaderFooter(docInfo);
			headerfooter.setHeader(docInfo.getTitle());
			headerfooter.setBf(bfChinese);
			writer.setPageEvent(headerfooter);
			// record header field
			document.open();
			List<ColumnEx> colNames = docInfo.getColumnlst();
			PdfPTable t = new PdfPTable(colNames.size());
			float[] widths = new float[colNames.size()];
			for (int i = 0; i < colNames.size(); i++) {
				widths[i] = colNames.get(i).getWidth();
			}
			t.setWidths(widths);
			float tbwidth = document.right() - document.left();
			t.setTotalWidth(tbwidth);
			t.setLockedWidth(true);
			t.getDefaultCell().setMinimumHeight(docInfo.getRowHeight());

			createColounHeader(t, docInfo.getHeaderlst());
			t.setHeaderRows(docInfo.getHeaderRow());
			headerfooter.t = t;
			int _MAX_ROWS = 1000;// 最大行数，之后清理
			int row_count = 0;// 初始值
			String tempheaderval = null;
			String tempfooterval = null;
			String temppageval = null;
			DataRow tempheaderRow = null;
			DataRow tempfooterRow = null;
			if (null != datalist && datalist.GetRowCount() > 0) {
				ColumnEx column;
				String tempstr;
				for (int i = 0; i < datalist.GetRowCount(); i++) {
					if (null != docInfo.getHeadercon()
							&& "" != docInfo.getHeadercon()) {
						if (!datalist.GetString(i, docInfo.getHeadercon())
								.equalsIgnoreCase(tempheaderval)) {
							tempheaderval = datalist.GetString(i,
									docInfo.getHeadercon());
							for (int hi = 0; hi < headers.GetRowCount(); hi++) {
								if (headers.GetString(hi,
										docInfo.getHeadercon())
										.equalsIgnoreCase(tempheaderval)) {
									tempheaderRow = headers.GetRow(hi);
									headerfooter.Headers = tempheaderRow;
									break;
								}
							}

						}

					}
					if (null != docInfo.getFootercon()
							&& "" != docInfo.getFootercon()) {
						if (!datalist.GetString(i, docInfo.getFootercon())
								.equalsIgnoreCase(tempfooterval)) {
							tempfooterval = datalist.GetString(i,
									docInfo.getFootercon());
							for (int hi = 0; hi < footers.GetRowCount(); hi++) {
								if (footers.GetString(hi,
										docInfo.getFootercon())
										.equalsIgnoreCase(tempfooterval)) {
									tempfooterRow = footers.GetRow(hi);
									headerfooter.Footers = tempfooterRow;
									break;
								}
							}

						}
					}

					if (null != docInfo.getPagecon()
							&& "" != docInfo.getPagecon()) {
						if (temppageval == null) {
							temppageval = datalist.GetString(i,
									docInfo.getPagecon());
						}
						if (!datalist.GetString(i, docInfo.getPagecon())
								.equalsIgnoreCase(temppageval)) {
							temppageval = datalist.GetString(i,
									docInfo.getPagecon());

							document.add(t);
							// delete _MAX_ROWS from table to free memory
							t.deleteBodyRows();
							// let iText manage when table header written
							t.setSkipFirstHeader(true);// 防止释放后一页出现两次表头
							document.newPage();
							writer.setPageEmpty(false);
							if (null != docInfo.getTitlecon()
									&& "" != docInfo.getTitlecon()) {
								headerfooter.setHeader(String.format(
										docInfo.getTitle(),
										datalist.GetString(i,
												docInfo.getTitlecon())));
							} else {
								headerfooter.setHeader(docInfo.getTitle());
							}
							createColounHeader(t, docInfo.getHeaderlst());
							t.setHeaderRows(docInfo.getHeaderRow());
						}
					}

					for (int j = 0; j < colNames.size(); j++) {
						column = colNames.get(j);
						PdfPCell tempcell;
						tempstr = null;
						try {
							if (column.getDataType() == SimpDataType.dateType) {
								/*
								 * tempstr = datalist.GetDateString(i,
								 * column.getColName(), column.formatStr);
								 */
								Date date = new SimpleDateFormat(
										column.formatStr).parse(datalist
										.GetString(i, column.getColName()));
								tempstr = new SimpleDateFormat(column.formatStr)
										.format(date);

							} else if (column.getDataType() == SimpDataType.doubleType) {
								DecimalFormat df = new DecimalFormat(
										column.formatStr);
								tempstr = df.format(datalist.GetString(i,
										column.getColName()));
							} else {
								tempstr = datalist.GetString(i,
										column.getColName());
							}

							if ("".equals(tempstr)) {
								tempstr = column.defValue;
							}

							if (column.getDataType() == SimpDataType.imgType) {
								Image img = Image.getInstance(tempstr);
								tempcell = new PdfPCell(img);
							} else {
								tempcell = new PdfPCell(new Paragraph(tempstr,
										textfont));
							}
							if (docInfo.getRowHeight() > 0) {
								tempcell.setMinimumHeight(docInfo
										.getRowHeight());
							}
							tempcell.setHorizontalAlignment(column
									.getHorAlignment());
							tempcell.setVerticalAlignment(column
									.getVerAlignment());
						} catch (Exception e) {
							tempcell = new PdfPCell(new Paragraph(tempstr,
									textfont));
						}
						t.addCell(tempcell);

					}

					if (++row_count % _MAX_ROWS == 0) {
						// datatable是我的一个PdfPTable的new出来的一个实例
						// add table to Document
						document.add(t);
						// delete _MAX_ROWS from table to free memory
						t.deleteBodyRows();
						// let iText manage when table header written
						t.setSkipFirstHeader(true);// 防止释放后一页出现两次表头。

					}

				}
			} else {
				document.add(t);
			}

			if (row_count % _MAX_ROWS > 0) {
				document.add(t);
			}

			document.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void genDetailPDF(DataTable datalist, DataTable detailList,
			DataTable headers, DataTable footers, String path) {

		Font textfont = new Font(bfChinese, docInfo.getDefFontSize(),
				Font.NORMAL);

		FileOutputStream out;
		try {
			out = new FileOutputStream(new File(path));
			PdfWriter writer = PdfWriter.getInstance(document, out);

			ReportHeaderFooter headerfooter = new ReportHeaderFooter(docInfo);
			headerfooter.setHeader(docInfo.getTitle());
			headerfooter.setBf(bfChinese);
			writer.setPageEvent(headerfooter);
			// record header field
			document.open();
			List<ColumnEx> colNames = docInfo.getColumnlst();
			float[] widths = new float[colNames.size()];
			for (int i = 0; i < colNames.size(); i++) {
				widths[i] = colNames.get(i).getWidth();
			}
			PdfPTable t = new PdfPTable(docInfo.getWidths());
			float tbwidth = document.right() - document.left();
			t.setTotalWidth(tbwidth);
			t.setLockedWidth(true);
			t.getDefaultCell().setMinimumHeight(docInfo.getRowHeight());

			int _MAX_ROWS = 1000;// 最大行数，之后清理
			int row_count = 0;// 初始值
			String tempheaderval = null;
			String tempfooterval = null;
			DataRow tempheaderRow = null;
			DataRow tempfooterRow = null;
			List<DetailHeaderEx> detailHeaderEx = docInfo.getDetailHeaderlst();
			if (null != datalist && datalist.GetRowCount() > 0) {
				ColumnEx column;
				String tempstr;
				for (int i = 0; i < datalist.GetRowCount(); i++) {
					if (null != docInfo.getHeadercon()
							&& "" != docInfo.getHeadercon()) {
						if (!datalist.GetString(i, docInfo.getHeadercon())
								.equalsIgnoreCase(tempheaderval)) {
							tempheaderval = datalist.GetString(i,
									docInfo.getHeadercon());
							for (int hi = 0; hi < headers.GetRowCount(); hi++) {
								if (headers.GetString(hi,
										docInfo.getHeadercon())
										.equalsIgnoreCase(tempheaderval)) {
									tempheaderRow = headers.GetRow(hi);
									headerfooter.Headers = tempheaderRow;
									break;
								}
							}

						}

					}
					if (null != docInfo.getFootercon()
							&& "" != docInfo.getFootercon()) {
						if (!datalist.GetString(i, docInfo.getFootercon())
								.equalsIgnoreCase(tempfooterval)) {
							tempfooterval = datalist.GetString(i,
									docInfo.getFootercon());
							for (int hi = 0; hi < footers.GetRowCount(); hi++) {
								if (footers.GetString(hi,
										docInfo.getFootercon())
										.equalsIgnoreCase(tempfooterval)) {
									tempfooterRow = footers.GetRow(hi);
									headerfooter.Footers = tempfooterRow;
									break;
								}
							}

						}
					}
					Font keyfont = new Font(bfChinese, 8, Font.BOLD);
					for (int di = 0; di < detailHeaderEx.size(); di++) {

						DetailHeaderEx headerEx = detailHeaderEx.get(di);
						keyfont = new Font(bfChinese, 8, Font.BOLD);
						if (headerEx.getFontSize() > 0) {
							keyfont.setSize(headerEx.getFontSize());
						}
						if (null != headerEx.getFontColor()) {
							keyfont.setColor(headerEx.getFontColor());
						}
						PdfPCell tempcell = new PdfPCell(new Paragraph(
								headerEx.getNameText(), keyfont));
						if (null != headerEx.getFgColor()) {
							tempcell.setBackgroundColor(headerEx.getFgColor());
						}
						if (headerEx.getColSpan() > 0) {
							tempcell.setColspan(headerEx.getColSpan());
						}
						if (headerEx.getRowSpan() > 0) {
							tempcell.setRowspan(headerEx.getRowSpan());
						}
						if (headerEx.getHeight() > 0) {
							tempcell.setMinimumHeight(headerEx.getHeight());
						}
						tempcell.setHorizontalAlignment(headerEx
								.getHorAlignment());
						tempcell.setVerticalAlignment(headerEx
								.getVerAlignment());
						t.addCell(tempcell);
						if (null != headerEx.colName) {
							if (headerEx.getDataType() == SimpDataType.TableType) {
								PdfPTable dt = new PdfPTable(widths);
								PdfPCell dtempcell;
								createColounHeader(dt, docInfo.getHeaderlst());
								for (int dk = 0; dk < detailList.GetRowCount(); dk++) {
									if (detailList.GetString(dk,
											headerEx.colName).equalsIgnoreCase(
											datalist.GetString(i,
													headerEx.colName))) {
										for (int j = 0; j < colNames.size(); j++) {
											column = colNames.get(j);
											tempstr = null;
											try {
												if (column.getDataType() == SimpDataType.dateType) {
													Date date = new SimpleDateFormat(
															column.formatStr)
															.parse(detailList
																	.GetString(
																			dk,
																			column.getColName()));
													tempstr = new SimpleDateFormat(
															column.formatStr)
															.format(date);

												} else if (column.getDataType() == SimpDataType.doubleType) {
													DecimalFormat df = new DecimalFormat(
															column.formatStr);
													tempstr = df
															.format(detailList
																	.GetString(
																			dk,
																			column.getColName()));
												} else {
													tempstr = detailList
															.GetString(
																	dk,
																	column.getColName());
												}

												if ("".equals(tempstr)) {
													tempstr = column.defValue;
												}

												if (column.getDataType() == SimpDataType.imgType) {
													Image img = Image
															.getInstance(tempstr);
													dtempcell = new PdfPCell(
															img);
												} else {
													dtempcell = new PdfPCell(
															new Paragraph(
																	tempstr,
																	textfont));
												}
												if (docInfo.getRowHeight() > 0) {
													dtempcell
															.setMinimumHeight(docInfo
																	.getRowHeight());
												}
												dtempcell
														.setHorizontalAlignment(column
																.getHorAlignment());
												dtempcell
														.setVerticalAlignment(column
																.getVerAlignment());
											} catch (Exception e) {
												dtempcell = new PdfPCell(
														new Paragraph(tempstr,
																textfont));
											}
											dt.addCell(dtempcell);

										}
									}
								}
								tempcell = new PdfPCell(dt);

							} else {
								if (headerEx.getDataType() == SimpDataType.dateType) {
									Date date = new SimpleDateFormat(
											headerEx.formatStr)
											.parse(datalist.GetString(i,
													headerEx.getColName()));
									tempstr = new SimpleDateFormat(
											headerEx.formatStr).format(date);

								} else if (headerEx.getDataType() == SimpDataType.doubleType) {
									DecimalFormat df = new DecimalFormat(
											headerEx.formatStr);
									tempstr = df.format(datalist.GetString(i,
											headerEx.getColName()));
								} else {
									tempstr = datalist.GetString(i,
											headerEx.getColName());
								}

								if ("".equals(tempstr)) {
									tempstr = headerEx.defValue;
								}

								if (headerEx.getDataType() == SimpDataType.imgType) {
									Image img = Image.getInstance(tempstr);
									tempcell = new PdfPCell(img);
								} else {
									tempcell = new PdfPCell(new Paragraph(
											tempstr, textfont));
								}
							}
							if (docInfo.getRowHeight() > 0) {
								tempcell.setMinimumHeight(docInfo
										.getRowHeight());
							}
							tempcell.setHorizontalAlignment(headerEx
									.getHorAlignment());
							tempcell.setVerticalAlignment(headerEx
									.getVerAlignment());

							t.addCell(tempcell);

						}

					}

					if (++row_count % _MAX_ROWS == 0) {
						// datatable是我的一个PdfPTable的new出来的一个实例
						// add table to Document
						document.add(t);
						// delete _MAX_ROWS from table to free memory
						t.deleteBodyRows();
						// let iText manage when table header written
						t.setSkipFirstHeader(true);// 防止释放后一页出现两次表头。

					}

				}
			} else {
				document.add(t);
			}

			if (row_count % _MAX_ROWS > 0) {
				document.add(t);
			}

			document.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void createColounHeader(PdfPTable t, List<HeaderEx> headerList) {
		Font keyfont = new Font(bfChinese, 8, Font.BOLD);

		// t.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
		for (int i = 0; i < headerList.size(); i++) {
			HeaderEx headerEx = headerList.get(i);
			keyfont = new Font(bfChinese, 8, Font.BOLD);
			if (headerEx.getFontSize() > 0) {
				keyfont.setSize(headerEx.getFontSize());
			}
			if (null != headerEx.getFontColor()) {
				keyfont.setColor(headerEx.getFontColor());
			}
			PdfPCell tempcell = new PdfPCell(new Paragraph(
					headerEx.getNameText(), keyfont));
			if (null != headerEx.getFgColor()) {
				tempcell.setBackgroundColor(headerEx.getFgColor());
			}
			if (headerEx.getColSpan() > 0) {
				tempcell.setColspan(headerEx.getColSpan());
			}
			if (headerEx.getRowSpan() > 0) {
				tempcell.setRowspan(headerEx.getRowSpan());
			}
			if (headerEx.getHeight() > 0) {
				tempcell.setMinimumHeight(headerEx.getHeight());
			}
			tempcell.setHorizontalAlignment(headerEx.getHorAlignment());
			tempcell.setVerticalAlignment(headerEx.getVerAlignment());
			t.addCell(tempcell);
		}

	}

}
